In this article you will learn about how to create web services APIs using PHP. Iif you are working with web services, you need to know about how we can POST and Receive JSON Data using cURL in PHP. Sending and Receiving JSON data via POST Request is most important functionality in PHP. It’s make easy to POST JSON data to APIs url and receive response in JSON data format. So, Today we will learn about “How to POST and Receive JSON Data using cURL in PHP”.
Let’s Start to send JSON data via POSt Request with PHP cURL:
In the following example code, i will show you HTTP POST request and send JSON data to URL with cURL function.
Step-1: First we will specify URL ($url) where the JSON data need to be send.
Step-2: Initiate cURL resource using curl_init().
step-3: encode PHP array data into aJSON string using json_encode().
step-4: Attach JSON data to the POSt field using the CURLOPT_POSTFIELDS option.
step-5: set header option to Content-Type: application/json
step-6: Return response as string CURL_RETURNTRANSFER option
Step-7: Finally curl_exec() function is used to execute the POST request api url.
index.php
In the following example code, We will pass POST data on API URL as JSON format.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php $id=120; $name="Tutorialswebsite"; $address="Sultanpur, New Delhi"; $phone=9999999999; //API URL $url="localhost/doctopdf/test.php"; $data = array("id" => $id, "name" => $name, "address" => $address,"phone"=>$phone); $ch = curl_init( $url ); # Setup request to send json via POST. $payload = json_encode( array( "customer"=> $data ) ); curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload ); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); # Return response instead of printing. curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); # Send request. $result = curl_exec($ch); curl_close($ch); # Print response. echo "<pre>" . $result. "</pre>"; ?> |
test.php
In the following code, We will Receive JSON POST data using PHP
jsone_decode() function is used to decode JSON data into array format and file_get_content() function is used to receivedata in readable format
2 3 4 5 6 7 8 |
<?php header("Content-Type:application/json"); $data = json_decode(file_get_contents('php://input'), true); print_r($data); ?> |
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co